package com.xht.handler.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xht.domain.entity.LoginUser;
import com.xht.enums.AppHttpCodeEnum;
import com.xht.exception.SystemExceptin;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    private static final Logger log = LoggerFactory.getLogger(MyMetaObjectHandler.class);

    @Override
    public void insertFill(MetaObject metaObject) {

        Long id = 1L;
        try {
            SecurityContext context = SecurityContextHolder.getContext();
            Authentication authentication = context.getAuthentication();
            LoginUser loginUser = null;
            if (authentication != null) {
                Object principal = authentication.getPrincipal();
                loginUser = (LoginUser) principal;
            }
            //LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (loginUser != null) {
                id = loginUser.getUser().getId();
            }

        } catch (Exception e) {
            throw new SystemExceptin(AppHttpCodeEnum.USERIDERRO);
        }

        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("createBy", id, metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", id, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
        //this.setFieldValByName("updateBy", SecurityUtils.getUserId(), metaObject);
    }
}